package org.jeecg.modules.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.trtc.v20190722.TrtcClient;
import com.tencentcloudapi.trtc.v20190722.models.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.modules.doctor.entity.DoctorWxUserinfoRelation;
import org.jeecg.common.modules.doctor.service.IDoctorWxUserinfoRelationService;
import org.jeecg.common.modules.wx.entity.WxUserinfo;
import org.jeecg.common.modules.wx.service.IWxUserinfoService;
import org.jeecg.common.util.result.Result;
import org.jeecg.common.util.result.ResultMapper;
import org.jeecg.modules.config.CustomProperties;
import org.jeecg.modules.vo.request.StartMCUMixTranscodeRequestVo;
import org.springframework.cache.support.NullValue;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

/**
 * @author guoyh
 * @ClassName ApiVideoService
 * @Description
 * @since 2020/9/13 16:15
 **/
@Service
@Slf4j
public class ApiVideoService {

    @Resource
    private IDoctorWxUserinfoRelationService doctorWxUserinfoRelationService;
    @Resource
    private CustomProperties customProperties;
    @Resource
    private IWxUserinfoService wxUserinfoService;

    /**
     * 开启混流
     * @return
     */
    public Result<NullValue> startMCUMixTranscode(StartMCUMixTranscodeRequestVo requestVo){
        DoctorWxUserinfoRelation relation = doctorWxUserinfoRelationService.getByGroupId(requestVo.getRoomId().toString());
        if (Objects.isNull(relation)){
            return ResultMapper.<NullValue>error().setMsg("未获取到房间信息");
        }
        WxUserinfo wxUserinfo = wxUserinfoService.getById(requestVo.getUserId());
        if (Objects.isNull(wxUserinfo)){
            return ResultMapper.<NullValue>error().setMsg("未获取到患者信息");
        }
        if (!StringUtils.equals(wxUserinfo.getOpenid(),relation.getOpenid())){
            return ResultMapper.<NullValue>error().setMsg("您无权开启混流");
        }
        startMCUMixTranscode(requestVo.getRoomId());
        return ResultMapper.ok();
    }

    private void startMCUMixTranscode(Long roomId){
        Long appid = customProperties.getVideo().getAppid();
        String secretId = customProperties.getVideo().getSecretId();
        String secretKey = customProperties.getVideo().getSecretKey();
        String fileName = String.format("%s_%s_%s", LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")),roomId, IdUtil.fastSimpleUUID());
        Credential credential = new Credential(secretId,secretKey);
        TrtcClient trtcClient = new TrtcClient(credential,"ap-beijing");
        StartMCUMixTranscodeRequest startMCUMixTranscodeRequest = new StartMCUMixTranscodeRequest();
        startMCUMixTranscodeRequest.setSdkAppId(appid);
        startMCUMixTranscodeRequest.setRoomId(roomId);
        OutputParams outputParams = new OutputParams();
        outputParams.setStreamId(roomId.toString());
        outputParams.setPureAudioStream(0L);
        outputParams.setRecordId(fileName);
        outputParams.setRecordAudioOnly(0L);
        startMCUMixTranscodeRequest.setOutputParams(outputParams);
        EncodeParams encodeParams = new EncodeParams();
        encodeParams.setAudioSampleRate(16000L);
        encodeParams.setAudioBitrate(500L);
        encodeParams.setAudioChannels(1L);
        encodeParams.setVideoWidth(1024L);
        encodeParams.setVideoHeight(768L);
        encodeParams.setVideoBitrate(5000L);
        encodeParams.setVideoFramerate(48L);
        encodeParams.setVideoGop(1L);
        startMCUMixTranscodeRequest.setEncodeParams(encodeParams);

        LayoutParams layoutParams = new LayoutParams();
        layoutParams.setTemplate(0L);
        startMCUMixTranscodeRequest.setLayoutParams(layoutParams);
        try {
            StartMCUMixTranscodeResponse response = trtcClient.StartMCUMixTranscode(startMCUMixTranscodeRequest);
            log.info("开启混流，响应结果：{}", JSONUtil.toJsonStr(response));
        } catch (TencentCloudSDKException e) {
            log.info("开启混流失败,roomId:{}",roomId,e);
        }
    }
}
